package com.education.webservlet;

import com.education.db.HibernateSessionFactory;
import com.education.db.dao.InfoMajorDAO;
import com.education.db.domain.InfoMajor;
import com.education.service.bean.UserBean;
import com.education.util.Constant;
import org.hibernate.Transaction;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by Fan307 on 2016/11/7.
 */
@WebServlet(name = "AddMajorServlet")
public class AddMajorServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private Transaction tran;
    public AddMajorServlet() {
        super();
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding(Constant.CHAR_ENCODING);

        tran = HibernateSessionFactory.getSession().getTransaction();

        UserBean userBean = (UserBean) request.getSession().getAttribute("userBean");
        String ma_value = request.getParameter("ma_value");
        String ma_name = request.getParameter("ma_name");

        try {
            tran.begin();
            InfoMajorDAO infoMajorDAO = new InfoMajorDAO();
            InfoMajor infoMajor = new InfoMajor();
            infoMajor.setMaValue(ma_value);
            infoMajor.setMaName(ma_name);
            infoMajorDAO.save(infoMajor);
            request.getSession().setAttribute("UserBean", userBean);
            String info = String.format("添加成功，1秒后为您自动跳到添加分类页面！！<meta http-equiv='refresh' content='1;url=%s'",
                    request.getContextPath() + "/admin/addFiles.jsp");
            request.setAttribute("info", info);
            request.getRequestDispatcher("/Pages/message.jsp").forward(request, response);
            tran.commit();
        } catch (Exception e) {
            System.out.println(e.toString());
            tran.rollback();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    public void init() throws ServletException{

    }
}
